// app.js
let req = require('./utils/request.js').Request;
let util = require('./utils/util.js');
let API = require('./api.js').API;

const USER = {
  /**
   * 注册
   * @param {*} code 
   * @param {*} stuId 
   */
  register(code) {
    return new Promise(function (resolve, reject) {
      let params = '?';
      if (code != null) {
        params += 'code=' + code;
      }
      wx.getUserProfile({
        desc: '为了更好的服务,需要绑定微信',
        success: function (res) {
          req.postJson(API.register + params, res)
            .then(function (res) {
              util.msg(res.msg);
              if (res.code == 0) {
                return resolve(res.dataMap);
              } else return reject(res);
            })
            .catch(function (reason) {
              return reject(reason);
            });
        },
        fail: function (res) {
          return reject(res);
        }
      });
    });
  },
  /**
   * 登陆
   * @param {*} uid 
   * @param {*} token 
   */
  login(token) {
    return new Promise(function (resolve, reject) {
      //console.log(encodeURI(params));
      req.postForm(API.login, {
          token: token
        })
        .then(function (res) {
          util.msg(res.msg);
          if (res.code == 0) {
            return resolve(res.dataMap);
          } else return reject(res);
        }).catch(function (reason) {
          return reject(reason);
        });
    });
  },
  /**
   * 注销
   */
  logout(token) {
    return new Promise(function (resolve, reject) {
      req.delete(API.logout + "?token=" + token)
        .then(function (res) {
          util.msg(res.msg);
          let code = res.code;
          if (code == 0) {
            return resolve(res.dataMap);
          } else return reject(res);
        }).catch(function (reason) {
          return reject(reason);
        });
    });
  },
  /**
   * 绑定学号
   */
  bindStuId: function (token, stuId) {
    return new Promise(function (resolve, reject) {
      req.postForm(API.bindStuId, {
          token: token,
          stuId: stuId
        })
        .then(function (res) {
          //util.msg(res.msg);
          let code = res.code;
          if (code == 0) {
            return resolve(res);
          } else return reject(res);
        }).catch(function (reason) {
          return reject(reason);
        })
    });
  }

}

App({
  /**
   * 接入ws
   */
  connectWs: function () {
    let app = this;
    app.globalData.socketTask = wx.connectSocket({
      url: 'ws://localhost:8080/api/chat' + '?token=' + this.globalData.token,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.log("error:");
        console.log(res);
      }
    });
    app.globalData.socketTask.onOpen(function (res) {
      console.log(res);
    });
    app.globalData.socketTask.onError(function (res) {
      console.log(res);
    });
    app.globalData.socketTask.onMessage(function (res) {
      let online = '[];\'./';
      let offline = '/.\';][';
      //console.log(res);
      let data = JSON.parse(res.data);
      //判断是否为上下线通知who=2
      if (data.who == 2) {
        console.log(res);
        let id = data.id;
        if (data.message == online) {
          app.globalData.chatPeople.forEach(function (item) {
            if (item.id == id) {
              item.online = true;
            }
          });
          //通知对方自己在线
          let onlineMessage = {
            destinationId: id,
            sourceId: app.globalData.userInfo.id,
            message: online
          }
          app.globalData.socketTask.send({
            data: JSON.stringify(onlineMessage),
            success: function (res) {
              console.log(res);
            },
            fail:function(res){
              console.log(res);
            }
          });
        }
        if (data.message == offline) {
          app.globalData.chatPeople.forEach(function (item) {
            if (item.id == id) {
              item.online = false;
            }
          });
        }
      } else {
        //App里的onMessage过滤是否是陌生人的消息和未读消息
        //不监听正在聊天的好友发送来的信息
        if (data.sourceId != app.globalData.chatId) {
          //查看是否是陌生人发来的消息
          let stranger = !app.globalData.chatPeople.some(function (value) {
            return data.sourceId == value.id;
          });
          if (stranger) {
            //是陌生人增加聊天对话框
            //待补充对方是否在线的判断(online的值)
            //。。。。
            app.globalData.chatPeople.push({
              id: data.sourceId,
              offlineMessage: true,
              online:false
            });
          } else {
            //不是陌生人则是未读消息
            app.globalData.chatPeople.forEach(function (item) {
              if (data.sourceId == item.id) {
                item.offlineMessage = true;
              }
            });
          }
        }
      }

    });
  },

  onLaunch() {
    let app = this;
    this.globalData.token = wx.getStorageSync('token');


    //重来没有登录过
    if (!this.globalData.token) {
      wx.login({
        success: function (res) {
          let code = res.code;
          wx.showModal({
            title: '提示',
            content: '需要绑定微信',
            success: function (res) {
              if (res.confirm) {
                USER.register(code)
                  .then(function (data) {
                    app.globalData.userInfo = data.user;
                    app.globalData.token = data.token;
                    app.globalData.hasLogin = true;
                    wx.setStorageSync('token', data.token);
                    util.navigateTo('/pages/bindStudentNumber/bindStudentNumber');
                    app.connectWs();
                  })
                  .catch(function (reason) {
                    console.log(reason);
                  });
              }
            }
          });
        }
      });
    } else {
      USER.login(this.globalData.token)
        .then(function (data) {
          app.globalData.userInfo = data.user;
          app.globalData.hasLogin = true;
          app.connectWs();
        })
        .catch(function (reason) {
          console.log(reason);
          if (reason.code ==  1) {
            wx.login({
              success: function (res) {
                let code = res.code;
                wx.showModal({
                  title: '温馨提示',
                  content: '身份授权过期，需要重新授权',
                  success: (res) => {
                    if (res.confirm) {
                      USER.register(code)
                        .then(function (data) {
                          console.log(data);
                          app.globalData.userInfo = data.user;
                          app.globalData.hasLogin = true;
                          app.globalData.token = data.token;
                          wx.setStorageSync('token', data.token);
                          app.connectWs();
                        });
                    }
                  }
                });
              }
            })
          }
        });
    }
  },
  onShow() {
    if (this.globalData.hasLogin) {
      //this.connectWs();
    }
    let chatPeople=wx.getStorageSync('chatPeople');
    if(chatPeople!=''){
      this.globalData.chatPeople = chatPeople;
    }
  },
  onHide() {
    this.globalData.socketTask.close();
    console.log(this.globalData.chatPeople);
    //在线标志符归位
    this.globalData.chatPeople.forEach(function (item) {
      item.online = false;
    });
    wx.setStorageSync('chatPeople', this.globalData.chatPeople);
  },
  globalData: {
    hasLogin: false,
    userInfo: null,
    socketTask: null,
    chatPeople: [],
    chatId: null,
    token: ""
  }

});



module.exports = {
  USER
}